#! /bin/bash
#! ffmpeg -aspect 1:1 -i $1 -aspect 4:3 -target ntsc-dvd -b 3300k -ab 224k ./`basename $1`.mpg
logfile="./makempeg2.log"
usage() {
	echo "Usage: `basename $0` ab length [ -e | -r | -s ] infiles..."
	echo "  ab:"
	echo "		audio bitrate in Kibit/s"
	echo "  length:"
	echo "		estimated length in minutes of all video being put on dvd"
	echo "		if length is 0, length is total length of all infiles combined"
	echo "  -e:"
	echo "		forced efficiency mode"
	echo "		add 1% to bitrate"
	echo "  -r:"
	echo "		real mode"
	echo "		use unmodified bitrate"
	echo "  -s:"
	echo "		safe mode (default)"
	echo "		subtract 1% from bitrate"
	exit -1
}
log() {
	message="$@"
	echo $message
	echo `date +%H:%M:%S:%N` : $message >> $logfile
}
die() {
	log "error: $@"
	exit -2
}
[ "$#" -ge 3 ] || usage

mode="s" # safe mode is default
size=`echo "4.7*1000^3*8" | bc` # set size of dvd in b
audio=`echo "scale=5;$1 * 1024" | bc` # get rate of audio in b/s
length=`echo "$2 * 60" | bc` # set length

count=0
for arg in "$@"
do
	let count++
	if [ $count -eq 1 ]; then
		echo $arg | grep -E -q '^[0-9]+$' || die "invalid audio bitrate"
	elif [ $count -eq 2 ]; then
		echo $arg | grep -E -q '^[0-9]+$' || die "invalid length"
	elif [ $count -eq 3 ]; then
		if [ "$arg" == "-e" ]; then
			mode="e"
		elif [ "$arg" == "-r" ]; then
			mode="r"
		elif [ "$arg" == "-s" ]; then
			mode="s"
		fi
	fi
done

# calculate total length of dvd
if [ $length -eq 0 ]; then
	count=0
	for arg in "$@"
	do
		let count++
		if [ $count -ge 3 -a "$arg" != "-e" -a "$arg" != "-r" -a "$arg" != "-s" ]; then
			thislength=`mplayer -endpos 0.1 -vo null -ao null -identify "$arg" 2>&1 | grep ID_LENGTH | cut -d = -f 2`
			length=`echo "scale=5;$length+$thislength" | bc`
		fi
	done
fi

bitrate=`echo "scale=5;($size - ($audio * $length)) / $length" | bc`
log "size: $size b, audio: $audio b/s, length: $length s, video: $bitrate b/s, mode: $mode"
[ "$mode" == "e" ] && bitrate=`echo "scale=5;$bitrate+($bitrate*0.01)" | bc`
[ "$mode" == "s" ] && bitrate=`echo "scale=5;$bitrate-($bitrate*0.01)" | bc`
log "video: $bitrate b/s"
bitrate=`echo "scale=5;$bitrate/1024" | bc`
log "video: $bitrate Kibit/s"


# process each video
count=0
for arg in "$@"
do
	let count++
	if [ $count -ge 3 -a "$arg" != "-e" -a "$arg" != "-r" -a "$arg" != "-s" ]; then
		if [ -e "$arg" ]; then
			out=$arg		
			out=${out##*/} # chop path down to filename with ext
			out=${out%.*} # continue chop to filename with no ext
			out="'./$out.mpg'"
			newcommand="ffmpeg -aspect 1:1 -i '$arg' -aspect 4:3 -target ntsc-dvd -b ${bitrate}k -ab $1k -acodec mp2 $out;"
			#log "added command: $newcommand"
			commands="$commands $newcommand"
		else
			die "$arg is not a valid infile"
		fi
	fi
done

log "using commands: $commands"
eval $commands
